/**
 * Created by houjianhui on 2017/7/19.
 */
'use strict';
wmsCtrl.controller('reservoirCtrl',['$scope','reservoirService','dropDownService',function(scope,reservoirService,dropDownService){   //库区管理

    //新增库区 click
    scope.addReservoirClick = function(){
        scope.Tools.dialog({
            controller : 'reservoirCtrl.dialog',
            template : 'templates/locationManagement/reservoirManagement/reservoir-form.html',
            closeByDocument : false,
            closeByEscape : false,
            data : {
                dropDownDefault : {    //下拉框默认值
                    warehouse : {
                        whName: scope.userInfo.whName,
                        whCode:scope.userInfo.whCode
                    }
                }
            },
            width : 530,
            title : '新增库区',
            scope : scope
        })
    }
    //更新库区 click
    scope.modifyReservoirClick = function(){

        var indexArr = scope.Tools.getTableSelectItemIndex('.reservoirTable');  //获取table所选的下标

        if(indexArr.length == 0){
            scope.Tools.alert('请选择需要更新的数据');
            return;
        }

        if(indexArr.length > 1){
            scope.Tools.alert('只能选择一条数据进行更新');
            return;
        }

        reservoirService.getById(scope.reservoirList[indexArr[0]].zeId)
            .then(function(result){
                if(result.success){
                    scope.Tools.dialog({
                        controller : 'reservoirCtrl.dialog',
                        template : 'templates/locationManagement/reservoirManagement/reservoir-form.html',
                        closeByDocument : false,
                        closeByEscape : false,
                        data : {
                            dropDownDefault : {    //下拉框默认值
                                warehouse : {
                                    whName : result.data.zeWhName,
                                    whCode : result.data.zeWhCode
                                }
                            },
                            reservoir : result.data
                        },
                        width : 530,
                        title : '更新库区',
                        scope : scope
                    })
                }else{
                    scope.Tools.alert(result.message);
                }
            })
    }
    //删除库区
    scope.deleteWarehouseMaintenanceClick = function(){
        var zeIdArr = [];
        var indexArr = scope.Tools.getTableSelectItemIndex('.reservoirTable');  //获取table所选的下标
        var zoneIdList = scope.Tools.getDataTOIndex(indexArr,scope.reservoirList);
        if(zoneIdList.length == 0){
            scope.Tools.alert('请选择需要删除的数据');
            return;
        }

        scope.Tools.dialogConfirm('确定要删除选中的数据吗？')
            .then(function(res){
                if(res){
                    for(var i =0;i<zoneIdList.length;i++){
                        zeIdArr.push(zoneIdList[i].zeId);
                    }
                    reservoirService.deleteZoneNew(zeIdArr)
                        .then(function(result){
                            if(result.success){
                                scope.list(scope.listParam());
                                scope.Tools.alert('删除数据成功');
                            }else{
                                scope.Tools.alert(result.message);
                            }
                        })
                }
            })
    }
    //列表查询参数
    scope.listParam = function(){

        if(!scope.search){
            scope.search = {};
        }

        if(!scope.fristSelect){ //不是第一次查询 则设置当前页
            scope.search.pageNo = scope.pageNo;
        }else{  //第一次查询设置为　第一页
            scope.search.pageNo = scope.constant.pageNo;
        }

        scope.search.pageSize = scope.pageSize;    //设置最大页
        return scope.search;
    }

    //列表
    scope.fristSelect = true;   //判断是否是第一次查询
    scope.list = function(params){
        //设置分页参数
        if(!params){
            params = {};
        }
        params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
        params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo

        reservoirService.list(params)
            .then(function(result){
                if(result.success){
                    scope.reservoirList = result.data.wmsZoneList;
                    if(scope.fristSelect){
                        scope.Tools.page(document.getElementById('pages'),{
                            pages : result.data.wmsZoneBO.totalPage,
                            curr : result.data.wmsZoneBO.pageNo,
                            count : result.data.wmsZoneBO.totalRecord
                        },function(obj, first){
                            scope.fristSelect = first;  //设置状态
                            //初始化多选框
                            scope.Tools.initCheckBox();
                            if(!first){ //判断不是第一次加载
                                var param = scope.listParam();
                                param.pageNo = obj.curr;    //当前页
                                param.pageSize = obj.limit; //最大页
                                scope.pageSize = obj.limit; //设置最大页
                                scope.pageNo = obj.curr; //设置当前页
                                scope.list(param);
                            }
                        })
                    }else{
                        //初始化多选框
                        scope.Tools.initCheckBox();
                    }

                }else{
                    scope.Tools.alert(result.message);
                }
            })
    }

    //列表
    scope.list();

    //查询 click
    scope.searchClick = function(){
        scope.fristSelect = true;   //设置为第一次查询
        scope.list(scope.listParam());
    }

    //刷新 click
    scope.refreshClick = function(){
        scope.searchClick();
    }

    //按下回车键查询
    scope.searchListKeyDown = function(e){
        var keycode = window.event ? e.keyCode:e.which;
        if(keycode == 13){  //回车键
            scope.fristSelect = true;   //设置为第一次查询
            scope.list(scope.listParam());
            e.preventDefault();
        }
    }
}])
.controller('reservoirCtrl.dialog',['$scope','reservoirService','dropDownService',function(scope,reservoirService,dropDownService){   //库区管理 dialog

    scope.saveOrUpdateReservoirClick = function(){  //新增库区

        scope.ngDialogData.reservoir.zeWhName = scope.ngDialogData.dropDownDefault.warehouse.whName;
        scope.ngDialogData.reservoir.zeWhCode = scope.ngDialogData.dropDownDefault.warehouse.whCode;

        //存在id 则为更新 不存在 新增
        if(scope.ngDialogData.reservoir.zeId){  //更新
            reservoirService.update(scope.ngDialogData.reservoir)
                .then(function(result){   //新增库区
                    if(result.success){
                        scope.Tools.alert('更新库区成功');
                        scope.list();
                        scope.closeThisDialog();
                    }else{
                        scope.Tools.alert(result.message);
                    }
                })
        }else{  //新增
            reservoirService.add(scope.ngDialogData.reservoir)
                .then(function(result){   //新增库区
                    if(result.success){
                        scope.Tools.alert('新增库区成功');
                        scope.$parent.fristSelect = true;   //设置为第一次查询
                        scope.list();
                        scope.closeThisDialog();
                    }else{
                        scope.Tools.alert(result.message);
                    }
                })
        }
    }
}])
.controller('repairBillCtrl',['$scope','$rootScope','repairBillService','dropDownService',function(scope,rootScope,repairBillService,dropDownService){  //维修单管理 controller

    /*状态数据*/
    scope.dropDownList = {
        repairType : scope.Tools.dropDown.repairTypeDropDown.concat(),   //维修类型
        repairStatus : scope.Tools.dropDown.repairStatusDropDown.concat(), //维修状态
        repairResult : scope.Tools.dropDown.repairResultDropDown.concat()   //维修结果
    }

    scope.dropDownList.repairType.unshift(scope.constant.defaultDropDownNullData);   //插入维修状态
    scope.dropDownList.repairStatus.unshift(scope.constant.defaultDropDownNullData);   //插入维修状态
    scope.dropDownList.repairResult.unshift(scope.constant.defaultDropDownNullData);   //插入维修结果

    //设置默认值
    scope.dropDownDefault = {
        repairType : scope.dropDownList.repairType[0], //维修类型
        repairStatus : scope.dropDownList.repairStatus[0], //维修状态
        repairResult : scope.dropDownList.repairResult[0]   //维修结果
    }

    //列表查询参数
    scope.listParam = function(){

        if(!scope.search){
            scope.search = {};
        }
        scope.search.pageSize = scope.pageSize;    //设置最大页
        if(!scope.fristSelect){ //不是第一次查询 则设置当前页
            scope.search.pageNo = scope.pageNo;
        }else{  //第一次查询设置为　第一页
            scope.search.pageNo = scope.constant.pageNo;
        }

        if(scope.otherForm){    //展开了更多
            scope.search.rpType = scope.dropDownDefault.repairType.value;   //维修类型
            scope.search.rpStatus = scope.dropDownDefault.repairStatus.value;    //维修状态
            scope.search.rpRepairResult = scope.dropDownDefault.repairResult.value;//维修结果
            return scope.search;
        }else{
            return scope.search;
        }
    }

    //列表
    scope.fristSelect = true;   //判断是否是第一次查询
    scope.list = function(params){
        //设置分页参数
        if(!params){
            params = {};
        }
        params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
        params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo

        repairBillService.list(params)
            .then(function(result){
                if(result.success){

                    scope.repairBillList = result.data.wmsRepairList;
                    rootScope.repairBillList = result.data.wmsRepairList;
                    if(scope.fristSelect){
                        scope.Tools.page(document.getElementById('pages'),{
                            pages : result.data.wmsRepairQueryDTO.totalPage,
                            curr : result.data.wmsRepairQueryDTO.pageNo,
                            count : result.data.wmsRepairQueryDTO.totalRecord
                        },function(obj, first){
                            scope.fristSelect = first;  //设置状态
                            //初始化多选框
                            scope.Tools.initCheckBox();
                            if(!first){ //判断不是第一次加载
                                var param = scope.listParam();
                                param.pageNo = obj.curr;    //当前页
                                param.pageSize = obj.limit; //最大页
                                scope.pageSize = obj.limit; //设置最大页
                                scope.pageNo = obj.curr; //设置当前页
                                scope.list(param);
                            }
                        })
                    }else{
                        //初始化多选框
                        scope.Tools.initCheckBox();
                    }

                }else{
                    scope.Tools.alert(result.message);
                }
            })
    }

    //列表
    scope.list();
    rootScope.repairBillRefrsh =  scope.list;

    //查询 click
    scope.searchClick = function(){
        scope.fristSelect = true;   //设置为第一次查询
        scope.list(scope.listParam());
    }

    //按下回车键查询
    scope.searchListKeyDown = function(e){
        var keycode = window.event ? e.keyCode:e.which;
        if(keycode == 13){  //回车键
            scope.fristSelect = true;   //设置为第一次查询
            scope.list(scope.listParam());
            e.preventDefault();
        }
    }

    //更多条件
    scope.moreText = scope.constant.moreText.spread;
    scope.moreClick = function(){
        scope.otherForm = !scope.otherForm;
        if(scope.otherForm){
            scope.moreText = scope.constant.moreText.packUp;
        }else{
            scope.moreText = scope.constant.moreText.spread;
        }
    }

    //刷新 click
    scope.refreshClick = function(){
        scope.searchClick();
    }

    //重置 click
    scope.resetClick = function(){
        scope.search = {};
        scope.dropDownDefault.repairType = scope.dropDownList.repairType[0];
        scope.dropDownDefault.repairStatus = scope.dropDownList.repairStatus[0];
        scope.dropDownDefault.repairResult = scope.dropDownList.repairResult[0];
    }

    //提交维修 click
    scope.submitRepairBillClick = function(){

        var indexArr = scope.Tools.getTableSelectItemIndex('.repairTable');  //获取table所选的下标
        var lg =  indexArr.length;
        if(lg==0){
            scope.Tools.alert('未选择维修单!');
        } else if(lg>1){
            scope.Tools.alert('请单选！');
        } else if(lg==1) {
            scope.Tools.dialog({
                controller : 'repairBillCtrl.dialog',
                template : 'templates/maintenanceManagement/repairBill/repair-bill-form.html',
                closeByDocument : false,
                closeByEscape : false,
                data : {},
                width : 350,
                title : '提交维修单',
                scope : scope
            })
        }
    };
    // 打印维修单
    scope.printRepairBill = function(){
        var indexArr = scope.Tools.getTableSelectItemIndex('.repairTable');  //获取table所选的下标
        var id = rootScope.repairBillList[indexArr[0]].rpId;
        repairBillService.printRepair({
            rpId:id
        }).then(function(res){
            if(res.success){
            //     打开打印页面
                rootScope.rb_print_data = res.data;
                scope.Tools.dialog({
                    controller : 'printRepairBillCtrl',
                    template : 'templates/maintenanceManagement/repairBill/printRepairBill.html',
                    closeByDocument : false,
                    closeByEscape : false,
                    data : {},
                    width : 350,
                    title : '打印维修单',
                    scope : scope
                })
            } else {
                scope.Tools.alert('获取数据失败！');
            }
        })
    }
}])
    .controller('repairBillCtrl.dialog',['$scope','$rootScope','repairBillService','ngDialog',function(scope,rootScope,repairBillService,ngDialog){  //维修单 controller  dialog
    var indexArr = scope.Tools.getTableSelectItemIndex('.repairTable');  //获取table所选的下标
    var id = rootScope.repairBillList[indexArr[0]].rpId;
    scope.submitObj = {
        rpId :id ,
        rpRepairParty:'',
        rpEstimatedEndTime:'',
        remark:''
      }
      scope.isNull = function(obj){
          for(var k in obj){
              if(obj[k]==''){
                  return true
              }
          }
          return false
      }
    scope.saveOrUpdaterepairClick = function(){
        if(scope.isNull(scope.submitObj)){
            scope.Tools.alert('有未填项！')
        } else{
            repairBillService.submitRepair(scope.submitObj).then(function(res){
                if(res.success){
                    scope.Tools.alert(res.message);
                    setTimeout(function(){
                        ngDialog.closeAll()
                    },30)
                    //刷新列表
                    rootScope.repairBillRefrsh()
                } else {
                    scope.Tools.alert(res.message);
                    setTimeout(function(){
                        ngDialog.closeAll()
                    },30)
                }
            })
        }
    }
}])
    .controller('printRepairBillCtrl',['$scope','$rootScope','ngDialog',function(scope,rootScope,ngDialog){

    }])
    .controller('roleCtrl',['$scope','roleService','permissionsService',function(scope,roleService,permissionsService){   //角色 ctrl
    //更多条件默认值
    scope.moreText = scope.constant.moreText.spread;
    //更多条件
    scope.moreClick = function(){
        scope.otherForm = !scope.otherForm;
        if(scope.otherForm){
            scope.moreText = scope.constant.moreText.packUp;
        }else{
            scope.moreText = scope.constant.moreText.spread;
        }
    }

    /*状态数据*/
    scope.dropDownList = {
        status : scope.Tools.dropDown.statusDropDown.concat()    //状态
    }
    scope.dropDownList.status.unshift(scope.constant.defaultDropDownNullData);  //向前插入空值

    //设置默认值
    scope.dropDownDefault = {
        status :  scope.dropDownList.status[0] //状态默认值
    }

    //列表查询接口参数构造
    scope.listParam = function(){

        if(!scope.search){
            scope.search = {};
        }
        scope.search.pageSize = scope.pageSize;    //设置最大页
        if(!scope.fristSelect){ //不是第一次查询 则设置当前页
            scope.search.pageNo = scope.pageNo;
        }else{  //第一次查询设置为　第一页
            scope.search.pageNo = scope.constant.pageNo;
        }

        if(scope.otherForm){    //展开了更多
            scope.search.enable = scope.dropDownDefault.status.value;   //状态
            return scope.search;
        }else{  //没有展开
            return {};
        }
    }

    //列表
    scope.fristSelect = true;   //判断是否是第一次查询
    scope.list = function(params){
        //设置分页参数
        if(!params){
            params = {};
        }
        params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
        params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo;

        roleService.listRole(params)
            .then(function(result){
                if(result.success){
                    scope.roleList = result.data.dataList;
                    if(scope.fristSelect){
                        scope.Tools.page(document.getElementById('pages'),{
                            pages : result.data.page.totalPage,
                            curr : result.data.page.pageNo,
                            count : result.data.page.totalRecord
                        },function(obj, first){
                            scope.fristSelect = first;  //设置状态
                            //初始化多选框
                            scope.Tools.initCheckBox();
                            if(!first){ //判断不是第一次加载
                                var param = scope.listParam();
                                param.pageNo = obj.curr;    //当前页
                                param.pageSize = obj.limit; //最大页
                                scope.pageSize = obj.limit; //设置最大页
                                scope.pageNo = obj.curr; //设置当前页
                                scope.list(param);
                            }
                        })
                    }else{
                        //初始化多选框
                        scope.Tools.initCheckBox();
                    }
                }else{
                    scope.Tools.alert(result.message);
                }
            })
    }

    //列表
    scope.list();

    //查询 click
    scope.searchClick = function(){
        scope.fristSelect = true;   //设置为第一次查询
        scope.list(scope.listParam());
    }

    //重置 click
    scope.resetClick = function(){
        scope.search = {};
        scope.dropDownDefault.status = scope.dropDownList.status[0];
    }

    //刷新 click
    scope.refreshClick = function(){
        scope.searchClick();
    }

    //新增角色
    scope.addRoleClick = function(){
        //获取权限
        permissionsService.list()
            .then(function(result){
                if(result.success){
                    scope.Tools.dialog({
                        controller : 'roleCtrl.dialog',
                        template : 'templates/systemManagement/roleManagement/role-form.html',
                        closeByDocument : false,
                        closeByEscape : false,
                        data : {
                            permissions : result.data,   //权限
                            status : scope.Tools.dropDown.statusDropDown,    //状态
                            dropDownDefault : {
                                status : scope.Tools.dropDown.statusDropDown[0] //状态
                            }
                        },
                        width : 700,
                        title : '新增角色',
                        scope : scope
                    })
                }else{
                    scope.Tools.alert(result.message);
                }
            })
    }

    //更新角色 click
    scope.updateRoleClick = function(){

        var indexArr = scope.Tools.getTableSelectItemIndex('.roleTable');  //获取table所选的下标

        if(indexArr.length == 0){
            scope.Tools.alert('请选择角色数据');
            return;
        }

        if(indexArr.length > 1){
            scope.Tools.alert('只能选择一条角色数据');
            return;
        }

        //获取权限
        permissionsService.list()
            .then(function(result){
                if(result.success){
                    roleService.listPermiss({id : scope.roleList[indexArr[0]].id})
                        .then(function(permissResult){
                            if(permissResult.success){
                                scope.Tools.dialog({
                                    controller : 'roleCtrl.dialog',
                                    template : 'templates/systemManagement/roleManagement/role-form.html',
                                    closeByDocument : false,
                                    closeByEscape : false,
                                    data : {
                                        permissions : result.data,   //权限
                                        status : scope.Tools.dropDown.statusDropDown,    //状态
                                        dropDownDefault : {
                                            status : scope.Tools.dropDown.statusDropDown[0] //状态
                                        },
                                        role : scope.roleList[indexArr[0]], //角色
                                        rolePermiss : permissResult.data    //角色权限
                                    },
                                    width : 700,
                                    title : '新增角色',
                                    scope : scope
                                })
                            }else{
                                scope.Tools.alert(permissResult.message);
                            }
                        })
                }else{
                    scope.Tools.alert(result.message);
                }
            })
    }

    //删除角色 click
    scope.deleteRoleClick = function(){
        var indexArr = scope.Tools.getTableSelectItemIndex('.roleTable');  //获取table所选的下标

        var roleList = scope.Tools.getDataTOIndex(indexArr,scope.roleList);

        if(roleList.length == 0){
            scope.Tools.alert('请选择需要删除的数据');
            return;
        }

        scope.Tools.dialogConfirm('确定要删除选择的数据吗？')
            .then(function(res){
                if(res){
                    var ids = new Array();
                    angular.forEach(roleList,function(v,k){
                        ids.push(v.id);
                    });

                    roleService.deleteRole({roleIdList : ids})
                        .then(function(result){
                            if(result.success){
                                scope.Tools.alert('删除角色成功');
                                scope.list(scope.listParam());
                            }else{
                                scope.Tools.alert(result.message);
                            }
                        })
                }
            })
    }
}])
.controller('roleCtrl.dialog',['$scope','$timeout','roleService',function(scope,timeout,roleService){    //角色 ctrl dialog

    if(scope.ngDialogData.permissions){
        //递归循环赋值
        scope.recursivePermissions = function(permiss,rolePermiss){
            for(var i = 0; i < permiss.length; i++){
                for(var j = 0; j < rolePermiss.length;j++){
                    if(permiss[i].id == rolePermiss[j].id){
                        permiss[i].checked = true;
                    }
                    if(rolePermiss[j].childPermissionsBOList){
                        scope.recursivePermissions(permiss[i].childPermissionsBOList,rolePermiss[j].childPermissionsBOList);
                    }
                }
            }
        }
        timeout(function(){
            if(scope.ngDialogData.rolePermiss){ //判断是否是更新时候传递的用户所属角色
                scope.recursivePermissions(scope.ngDialogData.permissions,scope.ngDialogData.rolePermiss);
            }

            scope.permissionsZtree = $.fn.zTree.init(
                $('.permissionsZtree'),
                {
                    treeId:'originTree',
                    data : {
                        key : {
                            name : 'name',
                            children : 'childPermissionsBOList'
                        },
                        simpleData: {
                            enable : false,
                            idKey : "id",
                            pIdKey : "parentId",
                            rootPId : 0
                        }
                    },
                    check: {
                        enable: true,
                        chkStyle: "checkbox"
                    },
                    view :{
                        showLine : false,
                        showIcon : false,
                        showTitle: false,
                        selectedMulti : false  //设置不能多选
                    },
                    callback : {
                    }
                },
                scope.ngDialogData.permissions
            );
        },200);
    }

    //保存或更新角色 click
    scope.saveOrUpdateRoleClick = function(){

        if(!scope.ngDialogData.role){
            scope.ngDialogData.role = {};
        }

        var selectPermissionsNodes = scope.permissionsZtree.getCheckedNodes();   //权限
        scope.ngDialogData.role.enable = scope.ngDialogData.dropDownDefault.status.value;    //状态
        scope.ngDialogData.role.permissionsIdList = new Array();

        //封装权限
        for(var i = 0; i < selectPermissionsNodes.length; i++){
            scope.ngDialogData.role.permissionsIdList.push(selectPermissionsNodes[i].id);
        }

        //判断是否有id
        if(scope.ngDialogData.role.id){ //更新
            //删除属性
            delete scope.ngDialogData.role.isDeleted;
            delete scope.ngDialogData.role.createPerson;
            delete scope.ngDialogData.role.updatePerson;
            delete scope.ngDialogData.role.gmtCreate;
            delete scope.ngDialogData.role.gmtModified;
            roleService.updateRole(scope.ngDialogData.role)
                .then(function(result){
                    if(result.success){
                        scope.list(scope.listParam());
                        scope.Tools.alert('更新角色成功');
                        scope.closeThisDialog();
                    }else{
                        scope.Tools.alert(result.message);
                    }
                })
        }else{  //新增
            roleService.addRole(scope.ngDialogData.role)
                .then(function(result){
                    if(result.success){
                        scope.list(scope.listParam());
                        scope.Tools.alert('新增角色成功');
                        scope.closeThisDialog();
                    }else{
                        scope.Tools.alert(result.message);
                    }
                })
        }
    }
}])
    .controller('returnCarRegistrationCtrl',['$scope','$rootScope','$http','$timeout','ngDialog','returnCarRegistrationService','borrowCarRegistrationService','FileUploader',function($scope,$rootScope,$http,$timeout,ngDialog,returnCarRegistrationService,borrowCarRegistrationService,FileUploader){

        //新增
        $scope.addFlag = true;

        //还车时enter——search
        $rootScope.enter_search = function (e) {
            var keycode = window.event ? e.keyCode : e.which;//获取按键编码
            if (keycode == 13) {
                    returnCarRegistrationService.getDetail($scope.addObjRC.rcBorrowNo).then(function (result) {
                        if (result.success) {
                            $scope.addObjRC.wmsBorrowCarDetailList = result.data;
                        } else {
                            $scope.Tools.alert(result.message);
                        }
                    })
            }
        };

        if($rootScope.rcrAddFlag){

            $scope.addFlag = false; //编辑标志

            var rcidsArr = [];
            $('.wms_rcr_table').find('td i').each(function(i,obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var id = $(obj).parents('td').attr('rcid');
                    rcidsArr.push(id);
                }
            });

            returnCarRegistrationService.queryModifyDetail(rcidsArr[0]).then(function(data){
                if(data.success){
                    $scope.addObjRC = data.data[0];
                    $rootScope.rcrAddFlag = false;
                    if($scope.addObjRC.uploadPath){
                        $('.bcr-add-image').css("background","url("+$scope.addObjRC.uploadPath+")");
                        $('.bcr-add-image').css("background-size","100%");
                        $('.bcr-add-image').css("background-repeat","no-repeat");
                    }
                }
            });
        } else {
            $scope.addFlag = true;
        }

        $scope.addNew = function(){
            ngDialog.open({
                template: "templates/vehicleBorrowingManagement/layer/rcr-addNew.html",
                controller: "returnCarRegistrationCtrl",
                title: $rootScope.rcrAddFlag?'编辑还车登记':'还车登记',
                width:750
            });

            //加载完页面后再渲染下页面
            $timeout(function(){
                layui.use('form',function(){
                    var form = layui.form();
                    form.render();
                    //全选
                })

                //获取七牛token
                borrowCarRegistrationService.getUploadToken().then(function(result){
                    if (result.success) {
                        $scope.brc_token = result.data;
                        var imgKey = null;

                        var uploader = $rootScope.uploaderBRC = new FileUploader({
                            url: 'http://upload.qiniu.com/',
                            formData: [{
                                token: result.data
                            }],
                            queueLimit: 1,
                            autoUpload: true
                        });
                        $rootScope.brcFlag = true;
                        uploader.filters.push({
                            name: 'filterName',
                            fn: function (item /*{File|FileLikeObject}*/, options) {
                                $scope.imageUploadFlag = true;
                                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                            }
                        });
                        uploader.onSuccessItem = function (fileItem, response, status, headers) {
                            console.log("上传成功");
                            $scope.addObjRC.uploadKey = response.key;
                            $rootScope.uploadKey = response.key;
                            console.log($scope.addObjRC);

                            //获取图片url
                            borrowCarRegistrationService.getDownUrl(response.key).then(function (result) {
                                if (result.success) {

                                    $('.bcr-add-image').css("background","url("+result.data+")");
                                    $('.bcr-add-image').css("background-size","100%");
                                    $('.bcr-add-image').css("background-repeat","no-repeat");
                                }
                            }).finally(function () {
                                layer.close(index);
                            });
                        };
                        uploader.onProgressAll = function(progress) {
                            $("#progress"+$scope.index).css('width',(progress-10)*1.32+'px');
                            console.info('onProgressAll', progress);
                        };

                        uploader.onErrorItem = function (fileItem, response, status, headers) {
                            alert("文件" + fileItem.file.name + "上传失败！", "提示");
                            uploader.removeFromQueue(fileItem);
                            console.info('上传失败的文件', fileItem, response, status, headers);
                        };
                    }
                });

            },50);
        };
        $scope.rcrAddInput = false;
        //    添加新增单
        $scope.addObjRC = {
            rcReturnName:'',
            rcReturnDepartment:'',
            rcReturnTel:'',
            rcReturnDate:'',
            rcBorrowNo:'',
            wmsBorrowCarDetailList:[]

        };
        $scope.wmsTemp = {
            bdId:null,
            bdVin:'',
            bdMaterialName:'',
            bdCarSpecname:'',
            bdCarColorname:''
        };

        $scope.isNull = function(obj){
            for(var key in obj ){
                if(obj[key]==''){
                    return true
                }
            }
            return  false
        };

        $scope.addInputFlag = false;

        $scope.cueFlag = false;

        $scope.closeCue = function(){
            $scope.cueFlag = false;
        };

        //添加车辆信息
        $scope.addCar = function(){

            $scope.rcrAddInput = true;

            if( !$scope.isNull($scope.wmsTemp)){

                $scope.cueFlag = false;  // 提示信息

                $scope.addObjRC.wmsBorrowCarDetailList.push($scope.wmsTemp);
                //加载完页面后再渲染下页面
                $timeout(function(){
                    layui.use('form',function(){
                        var form = layui.form();
                        form.render();
                        //全选
                    })
                },50);

                $scope.wmsTemp = {
                    bdId:null,
                    bdVin:'',
                    bdMaterialName:'',
                    bdCarSpecname:'',
                    bdCarColorname:''
                };
            } else if($scope.addInputFlag) {
                $scope.cueFlag = true;
            }
            $scope.addInputFlag = true;  //控制表格添加显示
        };

        //删除车辆信息
        $scope.delCar = function(){
            var indexArr = [];
            $('.wmsCarInfo').find('td i').each(function(i,obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var index = $(obj).parents('td').attr('index');
                    indexArr.push(index);
                }
            });
            for(var i=0; i<indexArr.length;i++){
                $scope.addObjRC.wmsBorrowCarDetailList.splice(indexArr[i],1)
            }
        };

        //新增保存
        $scope.addSave = function(){
            $scope.addObjRC.uploadKey = $rootScope.uploadKey;
            if($scope.addObjRC.rcReturnName && $scope.addObjRC.rcReturnDepartment && $scope.addObjRC.rcReturnTel && $scope.addObjRC.rcReturnDate ){
                if($scope.addObjRC.rcBorrowNo || $scope.addObjRC.wmsBorrowCarDetailList.length>0 ) {
                    returnCarRegistrationService.add($scope.addObjRC).then(function(data){
                        if(data.success){
                            $scope.Tools.alert('新增保存成功');
                            ngDialog.closeAll();
                            $scope.getList();
                            $rootScope.rcDetail = [];
                        } else {
                            $scope.Tools.alert(data.message);
                        }
                    })
                } else{
                    $scope.Tools.alert('关联借车单号或车架号两者必须填写一项');
                }
            } else {
                $scope.Tools.alert('请完整填写还车人信息！');
            }
        };

        //保存编辑
        $scope.saveEdite = function(){
            if($rootScope.uploadKey){
                $scope.addObjRC.uploadKey = $rootScope.uploadKey;
            }
            returnCarRegistrationService.modify($scope.addObjRC).then(function(data){
                if(data.success){
                    $scope.Tools.alert('编辑保存成功');

                    $scope.addFlag = true;  //标记保存位置

                    ngDialog.closeAll();
                    $scope.getList();

                    //刷新后保存当前被选择项
                    $timeout(function(){
                        $('.wms_rcr_table').find('td i').eq($rootScope.currEQ).parent().addClass('layui-form-checked');
                        $('.wms_rcr_table').find('td i').eq($rootScope.currEQ).parents('tr').addClass('trSelect');
                    },200);

                    //    获取详细信息
                   returnCarRegistrationService.queryModifyDetail($rootScope.currEditeID).then(function(result){
                        if(result.success){
                            $rootScope.rcDetail = result.data[0].wmsBorrowCarDetailList;
                            console.log(result.data.wmsBorrowCarDetailList);
                            $timeout(function(){
                                $('.wms_rcr_table').find('td i').eq($rootScope.currEQ).parent().addClass('layui-form-checked');
                                $('.wms_rcr_table').find('td i').eq($rootScope.currEQ).parents('tr').addClass('trSelect');
                                $rootScope.currEQ = '';
                            },200);
                            $scope.getList();
                        }
                    })
                } else {
                    $scope.Tools.alert(data.message);
                }
            })
        };

        //关闭弹框
        //关闭弹框
        $scope.rcClose = function(){
            ngDialog.closeAll();
        };

        //删除
        $scope.delect = function(){
            var rcidsArr = [];
            $('.wms_rcr_table').find('td i').each(function(i,obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var id = $(obj).parents('td').attr('rcid');
                    rcidsArr.push(id);
                }
            });
            if(rcidsArr.length==0){
                $scope.Tools.alert('未选择借用单');
            } else{
                returnCarRegistrationService.del(rcidsArr).then(function(data){
                    if(data.success){
                        $scope.Tools.alert('删除成功');
                        $scope.getList();
                        $rootScope.rcDetail = [];
                    }  else {
                        $scope.Tools.alert(data.message);
                    }
                })
            }
        };

        //新增
        $scope.addrcrBill = function(){

            $rootScope.rcrAddFlag = false;
            $scope.addNew();
        };

        //    编辑
        $scope.edite = function(){
            var rcidsArr = [];
            $('.wms_rcr_table').find('td i').each(function(i,obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var id = $(obj).parents('td').attr('rcid');
                    rcidsArr.push(id);
                    $rootScope.currEQ = i;
                }
            });
            if(rcidsArr.length==1){
                //编辑前，获取相应数据
                $rootScope.currEditeID = rcidsArr[0];
                $rootScope.rcrAddFlag = true;
                $scope.addNew();
                //刷新后保存当前被选择项
                $timeout(function(){
                    $('.wms_rcr_table').find('td i').eq($rootScope.currEQ).parent().addClass('layui-form-checked');
                    $('.wms_rcr_table').find('td i').eq($rootScope.currEQ).parents('tr').addClass('trSelect');
                },200);
            } else if(rcidsArr.length==0){
                $scope.Tools.alert('未选择借用信息!');
            } else if (rcidsArr.length>1){
                $scope.Tools.alert('编辑只能选择一条!');
            }
        };

        layui.use('form',function(){
            var form = layui.form();
            form.render();
            //全选
            form.on('checkbox(allChoose)', function (data) {
                $(data.elem).parent().parent().parent().parent().parent().find('tr').toggleClass('trSelect');
                var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');
                child.each(function(index, item){
                    item.checked = data.elem.checked;
                    if(data.elem.checked){
                        $(item).parents('tr').addClass('trSelect');
                    } else {
                        $(item).parents('tr').removeClass('trSelect');
                    }
                });
                form.render('checkbox');
            });

            //  前面选择框选中
            form.on('checkbox(test)',function(data){
                if(data.elem.checked){
                    $(data.elem).parents('tr').addClass('trSelect');
                } else {
                    $(data.elem).parents('tr').removeClass('trSelect');
                }
            });
        });

        //    显示更多条件
        $scope.moreClick = function(){
            $('.otherForm').slideToggle(500);
        };
        $rootScope.mainList = '';


        $scope.fristSelect = true;
//    获取列表
        $scope.getList = function(){
            var params = {
                pageNo:$scope.pageNo || 1,
                pageSize:$scope.pageSize || 10
            };
            params = angular.extend(params,$scope.search);
            returnCarRegistrationService.returnLine(params)
                .then(function(result){
                    if(result.success){

                            $rootScope.mainList = result.data.wmsBorrowCarList;

                        if($scope.fristSelect){
                            $scope.Tools.page(document.getElementById('pages'),{
                                pages : result.data.totalPage,
                                curr : result.data.pageNo,
                                count : result.data.totalRecord
                            },function(obj, first){
                                $scope.fristSelect = first;  //设置状态

                                if(!first){ //判断不是第一次加载
                                    var param = {};
                                    param.pageNo = obj.curr;    //当前页
                                    param.pageSize = obj.limit; //最大页
                                    $scope.pageSize = obj.limit; //设置最大页
                                    $scope.pageNo = obj.curr; //设置当前页
                                    $scope.getList(param);
                                }
                            })
                        }
                    }else{
                        $scope.Tools.alert(result.message);
                    }
                })
        };
        $scope.getList();

        $rootScope.getList = $scope.getList;

        $scope.search ={};
        $scope.search.rcReturnName = '';
        $scope.search.rcReturnDepartment = '';
        $scope.search.returnStartTime = '';
        $scope.search.returnEndTime = '';

//    查询
        $scope.resetClick = function(){
            $scope.search.rcReturnName = '';
            $scope.search.rcReturnDepartment = '';
            $scope.search.returnStartTime = '';
            $scope.search.returnEndTime = '';

        };
//刷新
        $scope.refreshA = function(){
            $scope.pageSize = 10;
            $scope.resetClick();
            $scope.getList()
        };


        $scope.fristSelectT = true;
//    获取信息信息
        $scope.getDetail = function(e){
            var id =  angular.element(e.target).parent('tr').attr('rcid');
            returnCarRegistrationService.findReturnDetail(id).then(function(result){
                if(result.success){
                    $rootScope.rcDetail = result.data;
                } else {
                    $scope.Tools.alert(result.message);
                }
            })
        }
    }]);